package com.android.lovely.ui.fragment.role

import android.Manifest
import android.app.Activity
import android.net.Uri
import android.os.Build
import android.view.ViewGroup.MarginLayoutParams
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.android.lovely.R
import com.android.lovely.databinding.FragmentCreateRoleOneBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.ext.startImageCrop
import com.android.lovely.framework.BaseFragment
import com.android.lovely.room.role.CreateRole
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.android.lovely.ui.widget.CreateRoleTitleView.OnTitleClickListener
import com.android.lovely.user.UserManager
import com.google.android.material.internal.ViewUtils.hideKeyboard
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.keyboard.hideKeyboard
import com.kotlin.extensions.view.ViewExt.clickable
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/4/5 21:20
 */
class CreateRoleStep1Fragment: CreateRoleBaseFragment<FragmentCreateRoleOneBinding>() {

    private var uri: Uri? = null

    override fun initView() {
        mBinding.confirmButton.clickable {
            save()
            if (viewModel.isEdit) {
                viewLifecycleOwner.lifecycleScope.launch {
                    viewModel.save()
                    activity?.finish()
                }
            } else {
                viewModel.nextStep(0)
            }
        }
        if(viewModel.isEdit) {
            mBinding.confirmButton.text = getString(R.string.preview)
        }
        mBinding.name.addTextChangedListener {
            "${it?.length ?: 0}/50".also { mBinding.nameNum.text = it }
            checkEnable()
        }
        mBinding.male.clickable {
            selectGender(1)
        }
        mBinding.female.clickable {
            selectGender(2)
        }
        mBinding.unknown.clickable {
            selectGender(0)
        }
        mBinding.roleNsfw.isVisible = !UserManager.isC()
        mBinding.roleNsfw.addCallback(object : OnTitleClickListener{
            override fun onSelect(isOpen: Boolean) {

            }
        })

        mBinding.rolePublic.addCallback(object : OnTitleClickListener{
            override fun onSelect(isOpen: Boolean) {

            }
        })
        mBinding.slReal.clickable {
            selectType(2)
        }
        mBinding.slFantasy.clickable {
            selectType(1)
        }
        mBinding.ivAvatar.clickable {
            requireActivity().hideKeyboard()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                avatarSelectionLauncher.launch("image/*")
                return@clickable
            }
            storagePermissionRequestLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }

    override fun update(it: CreateRole) {
        if (it.avatar.isNotEmpty()) {
            mBinding.ivAvatar.loadWithPlaceholder(it.avatar)
            uri = it.avatar.toUri()
        }
        mBinding.name.setText(it.nickName)
        selectGender(it.gender)
        mBinding.roleNsfw.changeSwitch(it.nsfw)
        mBinding.rolePublic.changeSwitch(it.public)
        selectType(it.category)
        if (viewModel.isEdit) {
            mBinding.confirmButton.text = getString(R.string.preview)
        }
        checkEnable()
    }

    private fun selectGender(gender: Int) {
        when(gender) {
            1 -> {
                mBinding.male.isSelected = true
                mBinding.female.isSelected = false
                mBinding.unknown.isSelected = false
            }
            2 -> {
                mBinding.male.isSelected = false
                mBinding.female.isSelected = true
                mBinding.unknown.isSelected = false
            }
            else -> {
                mBinding.male.isSelected = false
                mBinding.female.isSelected = false
                mBinding.unknown.isSelected = true
            }
        }
        checkEnable()
    }

    private fun selectType(type: Int) {
        when(type) {
            2 -> {
                mBinding.tvReal.isSelected = true
                mBinding.tvFantasy.isSelected = false
            }
            else -> {
                mBinding.tvReal.isSelected = false
                mBinding.tvFantasy.isSelected = true
            }
        }
        checkEnable()
    }

    // 存储权限请求启动器
    private val storagePermissionRequestLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isPermissionGranted ->
        handleStoragePermissionRequestResult(isPermissionGranted)
    }

    // 裁剪活动启动器
    private val imageCropActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
        handleImageCropActivityResult(activityResult)
    }

    // 头像选择启动器
    private val avatarSelectionLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { selectedAvatarUri ->
        handleAvatarSelectionResult(selectedAvatarUri)
    }

    // 处理存储权限请求结果
    private fun handleStoragePermissionRequestResult(isPermissionGranted: Boolean) {
        if (isPermissionGranted) {
            startAvatarSelection()
        }
    }

    // 处理裁剪活动结果
    private fun handleImageCropActivityResult(activityResult: ActivityResult) {
        if (activityResult.resultCode == Activity.RESULT_OK) {
            val resultIntent = activityResult.data ?: return
            val croppedAvatarUri = UCrop.getOutput(resultIntent) ?: return
            updateAvatar(croppedAvatarUri)
        }
    }

    // 处理头像选择结果
    private fun handleAvatarSelectionResult(selectedAvatarUri: Uri?) {
        selectedAvatarUri?.let {
            startImageCrop(it)
        }
    }

    // 启动头像选择
    private fun startAvatarSelection() {
        avatarSelectionLauncher.launch("image/*")
    }

    // 启动图片裁剪
    private fun startImageCrop(avatarUri: Uri) {
        requireActivity().startImageCrop(imageCropActivityLauncher, avatarUri, isCircleCrop = false)
    }

    // 更新头像
    private fun updateAvatar(avatarUri: Uri) {
        this.uri = avatarUri
        checkEnable()
        mBinding.ivAvatar.loadWithPlaceholder(avatarUri, R.drawable.icon_default_avatar)
    }

    private fun checkEnable() {
        var isEnable = true
        if (uri?.toString().isNullOrEmpty()) {
            isEnable = false
        }
        if ((mBinding.name.text?.trim()?.length ?: 0) < 2) {
            isEnable = false
        }
        mBinding.confirmButton.isEnabled = isEnable
    }

    override fun save() {
        viewModel.updateRole {
            nickName = mBinding.name.text.toString()
            avatar = if (uri != null && (uri?.scheme == "http" || uri?.scheme == "https")) {
                uri.toString()
            } else {
                uri?.path.orEmpty()
            }
            if (mBinding.female.isSelected) gender = 2
            if (mBinding.male.isSelected) gender = 1
            if (mBinding.unknown.isSelected) gender = 0

            nsfw = mBinding.roleNsfw.getCheck() && !UserManager.isC()
            public = mBinding.rolePublic.getCheck()

            if (mBinding.tvReal.isSelected) category = 2
            if (mBinding.tvFantasy.isSelected) category = 1
        }
    }

    override fun hasEdit(): Boolean {
        return   viewModel.createRole?.category != (if(mBinding.tvReal.isSelected) 2 else 1)
                || viewModel.createRole?.nickName != mBinding.name.text.toString()
                || viewModel.createRole?.avatar !=  uri?.toString()
                || viewModel.createRole?.nsfw != mBinding.roleNsfw.isSelected
                || viewModel.createRole?.public != mBinding.rolePublic.getCheck()
    }

    override fun onKeyBoardChange(progress: Int) {
        mBinding.nestedScrollView.updateLayoutParams<MarginLayoutParams> {
            bottomMargin = (progress - bottomHeight - 10.dp).coerceAtLeast(0)
        }
    }

    override suspend fun initData() {

    }
}